<template>
  <div>
<!--    整卷练习{{subject_id}}{{currentItem}}{{tabsActiveName}}-->
    <el-tabs v-model="tabsActiveName" class="demo-tabs">
      <el-tab-pane v-for="item in subjectTabs" :label="item.name" :name="String(item.id)">
        <el-row class="row-bg model" justify="space-between">
          <el-col :span="10">
            <img style="width: 100%" src="../../../assets/tiku/zjlx.jpg">
          </el-col>
          <el-col :span="12">
            <div class="right-body">
              <div>抽题配置</div>
              <div class="head-right-contnet">
                <p>
                  系统随机抽取固定数量的试题组成试卷
                </p>
              </div>
              <div>
                <el-button type="primary" @click="loading_card">开始做题</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-dialog v-model="dialogLoadingVisible" :show-close="false" :close-on-click-modal="false" center title="自动组卷随机抽题中...">
          <el-progress :percentage="loading_num" />
        </el-dialog>
        <el-row class="model">
          <div class="ExerciseTab">
            <el-tabs v-model="activeName" class="demo-tabs">
              <el-tab-pane label="做题历史" name="default">
                <div v-if="examPaperList && examPaperList.rows && examPaperList.rows.length">
                  <div v-for="item in examPaperList.rows">
                    <div @click="lookExercise(item)" class="ExerciseItem">
                      <div>
                        <span class="name">{{item.name}}</span>
                      </div>
                      <div class="exam_history">
                        <span>{{ proxy.$filters.dateTimeFormat(item.createdAt) }}</span>
                        <span>正确率:{{item.correctS ? item.correctS:0}}%</span>
                        <span>客观题得分:{{item.objectiveScore}}</span>
                        <span>总分:{{item.totalScore}}</span>
                        <span style="color: rgba(11, 67, 128, 1);">{{item.fraction == null ? '未完成':'已完成'}}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-empty v-else description="暂无数据" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-row>
        <div v-if="examPaperList.pagination">
          <el-pagination
                  background
                  v-model:currentPage="currentPage"
                  :page-size="pageSize"
                  layout="total, prev, pager, next"
                  :total="examPaperList.pagination.count"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import * as moment from 'moment';
  import goBackHistory from "../../../utils/hook/goBackHistory";
  import {reactive,toRefs,getCurrentInstance,watch} from 'vue'
  import {useRouter} from "vue-router";
  import {createdChapter, examPaper, examPaperGenerate, exerciseTopicFilter, subjectList} from "../../../api/api";
  import {ElMessage, ElMessageBox} from 'element-plus'

  export default {
    name: "index",
    props:{
      subject_id:{
        type:Number
      },
      subject_name:{
        type:String,
        default:''
      },
      currentItem:{
        type:String
      },
      activeCourse:{
        type:String
      }
    },
    setup(props,{emit}){
      const { proxy } = getCurrentInstance()

      let data = reactive({
        subjectName:'',
        subjectTabs:[],
        tabsActiveName:null,
        activeName:'default',
        examPaperList:[],//做题历史记录
        pageSize:10,
        currentPage:1,
        dialogLoadingVisible:false,
        loading_num:20,
        isTopicNum:false
      })

      let router = useRouter();

      //查看是否有题目
      let getExerciseTopicFilter = () =>{
        exerciseTopicFilter({subjectID:Number(data.tabsActiveName),types:[],chapterIDs:[],num:1000}).then(res =>{
          console.log('当前科目下面有无题目',res)
        })
      }

      // getData().then(res =>{
      //   console.log('获取数据',res)
      // })

      //科目列表
      let getAllSubjectList = () =>{
        let course_id = localStorage.getItem('activeCourse')
        subjectList({courseID:course_id}).then(res =>{
          console.log('科目列表',res)
          data.subjectTabs = res.data;
          data.tabsActiveName = String(res.data[0].id);
          getExerciseTopicFilter();
        })
      }
      getAllSubjectList();

      //跳转至整卷练习并开始答题
      let toExamExercise = () =>{
        let params = router.currentRoute.value;
        let currentItem = props.currentItem;
        goBackHistory.addCurrentPageParams(params,currentItem)
        router.push({name:'ExamExercise',params:{subject_name:props.subject_name,id:Number(data.tabsActiveName),method:'examPaperGenerate',fraction:'null'}})
      }

      //做题历史
      let getExamPaper = () =>{
        examPaper({subjectID:data.tabsActiveName,page:data.currentPage,pageSize:data.pageSize}).then(res =>{
          console.log('做题历史记录',res)
          data.examPaperList = res.data
        })
      }

      // getExamPaper();

      let loading_card = () =>{
        if(data.isTopicNum){
          data.dialogLoadingVisible = true
          let itemr;
          itemr = setInterval(() =>{
            data.loading_num +=20;
            if(data.loading_num == 100){
              clearInterval(itemr)
              toExamExercise()
            }
          },1000)
        }else{
          ElMessage({type:'error',message:'该科目题数量不足'})
        }
      }

      const handleSizeChange = (val) => {
        console.log(`${val} items per page`)
        data.pageSize = val;
        getExamPaper();
      }
      const handleCurrentChange = (val) => {
        console.log(`current page: ${val}`)
        data.currentPage = val;
        getExamPaper();
      }

      let lookExercise = (item) =>{
        console.log('查看历史',item.id);
        if(item.fraction == null){
          ElMessageBox.confirm(
                  '是否继续上次未完成的试卷？',
                  '温馨提示',
                  {
                    confirmButtonText: '继续作答',
                    cancelButtonText: '退出',
                    type: 'warning',
                  }
          )
                  .then(() => {
                    let params = router.currentRoute.value;
                    let currentItem = props.currentItem;
                    goBackHistory.addCurrentPageParams(params,currentItem)
                    console.log(item)
                    router.push({name:'ExamExercise',params:{subject_name:props.subject_name,id:item.id,method:'lookExamPaper',fraction:item.fraction == null ? 'null':item.fraction}})
                  })
                  .catch(() => {

                  })
        }else{
          router.push({name:'ExamExercise',params:{subject_name:props.subject_name,id:item.id,method:'lookExamPaper',fraction:item.fraction == null ? 'null':item.fraction}})
        }
      }

      let getCreatedChapter = (subject_id) =>{
        createdChapter({subjectID:subject_id}).then(res =>{
          data.isTopicNum = res.data.map(item => item.topicNum).some(item => item > 0);
          console.log(data.isTopicNum)
        })
      }

      watch(() => data.tabsActiveName,() =>{
        if(data.tabsActiveName){
          getCreatedChapter(data.tabsActiveName);
          data.subjectName = data.subjectTabs.filter(item => item.id == Number(data.tabsActiveName))[0].name;
          emit('changeSubjectName',data.subjectName);
          getExamPaper();
        }
      })

      watch(() => props.activeCourse,() =>{
        getAllSubjectList();
      })


      return{
        proxy,
        loading_card,
        lookExercise,
        handleSizeChange,
        handleCurrentChange,
        ...toRefs(data),
        toExamExercise,
        getExamPaper
      }
    }
  }
</script>

<style scoped>
  .model{
    margin-bottom: 20px;
  }
  .exam_history :not(:last-child){
    margin-right: 20px;
  }
  .exam_history :not(:first-child){
    font-weight: 400;
    font-size: 12px;
    color: rgba(153, 153, 153, 1);
  }
  .exam_history :first-child{
    font-size: 12px;
    color: rgba(153, 153, 153, 1);
  }
  .ExerciseTab{
    width: 100%;
    margin-bottom: 20px;
  }
  .ExerciseItem .name{
    color: rgba(11, 67, 128, 1);
    font-size: 14px;
    font-weight: 400;
  }
  .ExerciseItem{
    display: flex;
    justify-content: space-between;
    /* height: 55px; */
    align-items: center;
    padding: 5px 20px;
    background-color:  rgba(248, 248, 248, 1);
    margin-bottom: 10px;
    border-radius: 10px;
    cursor: pointer;
  }
  .head-right-contnet{
    color: rgba(153, 153, 153, 1);
    font-size: 14px;
    margin: 20px 0px;
  }
  .head-right-contnet p{
    line-height: 30px;
  }
  .right-body{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
</style>
